/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 */
'use strict';
import { DOMParser } from 'xmldom';
import * as types from './actionTypes';
import {LoginValidate,OpenidLogin,OpenidRegister} from '../services/userServices';
import XmlHelper from '../utils/xmlhelper'

function requestLogin() {
    return {
      type: types.REQUEST_LOGIN
    };
}

function receiveLogin(userName,loginResult) {
    return {
      type: types.RECEIVE_LOGIN,
      userName,
      loginResult
    };
}

function requestOpenidLogin() {
    return {
      type: types.REQUEST_OPENID_LOGIN
    };
}

function openidLogin(catalog,loginResult) {
    return {
      type: types.RECEIVE_OPENID_LOGIN,
      catalog,
      loginResult
    };
}

function readUserToJson(xml) {
    const parser = new DOMParser();
    const xmlDoc = parser.parseFromString(xml);
    var jsonObj=null;
    try {
        var jsonStr= XmlHelper.xml2json(xmlDoc,'');
        jsonObj= JSON.parse(jsonStr);
    } catch (error) {
        return {result:0,msg:'解析成对象失败',userinfo:null};
    }
    if(jsonObj&&jsonObj.oschina&&jsonObj.oschina.result)
    {
        var _errorCode = 0;
        var _errorMessage = jsonObj.oschina.result.errorMessage['#cdata'];
        if(jsonObj.oschina.result.errorCode)
        {
            if(!isNaN(jsonObj.oschina.result.errorCode))
                _errorCode=Number(jsonObj.oschina.result.errorCode);
        }
        if(!_errorMessage)
            _errorMessage='请求未知错误'
        var _userInfo=null;
        
        if(jsonObj.oschina.user)
        {
            _userInfo = jsonObj.oschina.user;
        }
        return {result:_errorCode,msg:_errorMessage,userinfo:_userInfo};
    }
    else{
        return {result:0,msg:'请求返回异常',userinfo:null};
    }
}

export function SignIn(username,password)
{
    return dispatch => {
        dispatch(requestLogin());
        /*return  LoginValidate(username,password).then(function (response) {
            //console.warn(response.headers.get('Set-Cookie'));
            var txt=response.text();
            console.warn(JSON.stringify(txt));
            return {text:txt,cookie:response.headers.get('Cookie')} ;
        })*/
        return  LoginValidate(username,password).then(response => response.text())
        .then(text =>
        {
            var userJson = readUserToJson(text);
            if(userJson.result==0)
            {
                dispatch(receiveLogin('',userJson));
            }
            else
            {
                dispatch(receiveLogin(username,userJson));
            }
        }).catch((error)=>{dispatch(receiveLogin('',{result:0,msg:'系统异常!'+error,userinfo:null}))});
    } 
}

export function OpenidSignIn(catalog,openid_info)
{
    return dispatch => {
        dispatch(requestOpenidLogin());
        return  OpenidLogin(catalog,openid_info).then(response => response.text())
        .then(text =>
        {
            var userJson = readUserToJson(text);
            if(userJson.result==0)
            {
                dispatch(openidLogin(catalog,userJson));
            }
            else
            {
                dispatch(openidLogin(catalog,userJson));
            }
        }).catch((error)=>{dispatch(openidLogin(catalog,{result:0,msg:'系统异常!'+error,userinfo:null}))});
    } 
}

export function SignOut() {
    return {
      type: types.REQUEST_LOGOUT
    };
}

export function SetAuthrizatuon(userInfo) {
   return {
    type: types.SET_AUTHRIZATION,
    userInfo
  };
}

export function CleanAuthrizatuon() {
   global.storage.remove({key:'UserLoginInfo'});
   return {
    type: types.CLEAN_AUTHRIZATION
  };
}


